package com.extr.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.extr.controller.ExamController.ReportResult;
import com.extr.controller.UserCenterController.KnowledgePointAnalysisResult;
import com.extr.controller.UserCenterController.StatisticsResult;
import com.extr.controller.UserCenterController.TypeAnalysis;
import com.extr.controller.domain.AnswerSheetItem;
import com.extr.controller.domain.Message;
import com.extr.controller.domain.QuestionImproveResult;
import com.extr.controller.domain.QuestionQueryResult;
import com.extr.controller.domain.TeacherReadSheetItem;
import com.extr.domain.exam.ExamHistory;
import com.extr.domain.exam.ExamPaper;
import com.extr.domain.exam.HomeWork;
import com.extr.domain.exam.HomeWorkHistory;
import com.extr.domain.exam.PracticePaper;
import com.extr.domain.question.Field;
import com.extr.domain.question.KnowledgePoint;
import com.extr.domain.question.QuestionHistory;
import com.extr.domain.question.UserQuestionHistory;
import com.extr.domain.user.Role;
import com.extr.domain.user.User;
import com.extr.security.UserInfo;
import com.extr.service.ExamService;
import com.extr.service.HomeWorkService;
import com.extr.service.QuestionService;
import com.extr.service.UserService;
import com.extr.util.Page;
import com.extr.util.PagingUtil;
import com.extr.util.QuestionAdapter;
import com.extr.util.StandardPasswordEncoderForSha1;
import com.extr.util.xml.Object2Xml;

@Controller
public class UserController {

	public static final String SUCCESS_MESSAGE = "success";
	public static final String ERROR_MESSAGE = "failed";

	@Autowired
	private UserService userService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private HomeWorkService homeWorkService;
	@Autowired
	private ExamService examService;

	/**
	 * 用户登录页面
	 * 
	 * @return
	 */
	@RequestMapping(value = { "/user-login-page" }, method = RequestMethod.GET)
	public String loginPage(Model model, HttpServletRequest request,@RequestParam(value = "result", required = false, defaultValue = "") String result) {
		if("failed".equals(result)){
			model.addAttribute("result", "无效的用户名或者密码");
		}
		return "login";
	}

	/**
	 * 用户登录
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "/user-login" }, method = RequestMethod.POST)
	public @ResponseBody
	Message userLogin(@RequestBody User user) {
		//user.setCreate_date(new Date());
		Message message = new Message();
		try {
			userService.addUser(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			message.setResult("error");
			e.printStackTrace();
		}
		return message;
	}

	/**
	 * 用户注册成功页面
	 * 
	 * @return
	 */
	@RequestMapping(value = { "/regist-success/{username}" }, method = RequestMethod.GET)
	public String registerSuccessPage(@PathVariable String username, Model model) {
		//System.out.println("注册用户名："+username);
		try {
			//前端是通过get提交，可能包含中文，要转码
			username = java.net.URLDecoder.decode(username,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//System.out.println("注册用户名："+username);
		model.addAttribute("username", username);
		return "regist-success";
	}
	
	
	/**
	 * 用户信息查看
	 * 
	 * @return
	 */
	@RequestMapping(value = { "/user-detail/{username}" }, method = RequestMethod.GET)
	public String userDetailPage(@PathVariable String username, Model model) {
		model.addAttribute("username", username);
		User user = userService.getUserByName(username);
		int user_id = user.getId();
		List<Role> roleList = userService.getRoleListByUserId(user_id);
		boolean isManager = false;
		for(Role role : roleList){
			if(role.getId() == 1 || role.getName().indexOf("管理员") > -1)
				isManager = true;
		}
		if(!isManager)
			return "redirect:/student/usercenter";
		else
			return "redirect:/admin/sys-admin-list";
	}

	/**
	 * 用户注册页面
	 * 
	 * @return
	 */
	@RequestMapping(value = { "/user-register" }, method = RequestMethod.GET)
	public String registerPage(Model model) {
		List<Field> fieldList = questionService.getAllField(null);
		model.addAttribute("fieldList", fieldList);
		return "register";
	}

	/**
	 * 用户注册
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "/user-reg" }, method = RequestMethod.POST)
	public @ResponseBody
	Message userRegister(@RequestBody User user) {
		user.setCreate_date(new Date());
		String password = user.getPassword() + "{" + user.getUsername() + "}";
		PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
		String resultPassword = passwordEncoder.encode(password);
		user.setPassword(resultPassword);
		user.setEnabled("1");
		Message message = new Message();
		try {
			userService.addUser(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
			if(e.getMessage().equals("duplicate-username")){
				message.setResult(e.getMessage());
				message.setMessageInfo("用户名：" + user.getUsername() + "已经存在");
			}else
				message.setResult("错误！" + e.getClass().getName());
			e.printStackTrace();
		}
		return message;
	}
	
	
	/**
	 * 修改密码页面
	 * 
	 * @return
	 */
	@RequestMapping(value = { "student/change-password" }, method = RequestMethod.GET)
	public String changePasswordPage() {
		return "student/change-password";
	}
	
	@RequestMapping(value = { "change-pwd" }, method = RequestMethod.POST)
	public @ResponseBody Message changePassword(@RequestBody User user){
		Message message = new Message();
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		try{
			String password = user.getPassword() + "{" + userInfo.getUsername() + "}";
			PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
			String resultPassword = passwordEncoder.encode(password);
			user.setPassword(resultPassword);
			user.setUsername(userInfo.getUsername());
			userService.updateUser(user, null);
			//System.out.println(user.getFieldId());
		}catch(Exception e){
			e.printStackTrace();
			message.setResult(e.getClass().getName());
		}
		
		return message;
	}
	/**
	 * 修改个人资料页
	 * @return
	 */
	@RequestMapping(value = { "student/setting" }, method = RequestMethod.GET)
	public String settingPage(Model model) {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		User user = userService.getUserById(userInfo.getUserid());
		List<Field> fieldList = questionService.getAllField(null);
		model.addAttribute("fieldList", fieldList);
		model.addAttribute("user", user);
		return "student/setting";
	}
	
	@RequestMapping(value = { "setting" }, method = RequestMethod.POST)
	public @ResponseBody Message setting(@RequestBody User user){
		Message message = new Message();
		try{
			userService.updateUser(user, null);
			//修改用户信息之后，需要更新session
		}catch(Exception e){
			e.printStackTrace();
			message.setResult(e.getClass().getName());
		}
		return message;
	}
	
	
	/**
	 * 显示用户管理界面
	 * 
	 * @return
	 */
	@RequestMapping(value = { "admin/user-list" }, method = RequestMethod.GET)
	public String showUserListPage(Model model, HttpServletRequest request) {
		
		int index = 1;
		if(request.getParameter("page") != null)
			index = Integer.parseInt(request.getParameter("page"));
		Page<User> page = new Page<User>();
		page.setPageNo(index);
		page.setPageSize(20);
		
		List<User> userList = userService.getUserListByRoleId(3, page);
		String pageStr = PagingUtil.getPagelink(index, page.getTotalPage(), page.getTotalRecord(), "", "admin/user-list");
		model.addAttribute("userList", userList);
		model.addAttribute("pageStr", pageStr);
		return "admin/user-list";
	}
	
	/**
	 * 添加用户界面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/add-user", method = RequestMethod.GET)
	private String addUserPage(Model model, HttpServletRequest request) {
			
		List<Field> fieldList = questionService.getAllField(null);
		model.addAttribute("fieldList", fieldList);
		return "admin/add-user";
	}
	
	/**
	 * 添加用户
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "/admin/add-user" }, method = RequestMethod.POST)
	public @ResponseBody Message addUser(@RequestBody User user){
		user.setCreate_date(new Date());
		String password = user.getPassword() + "{" + user.getUsername() + "}";
		PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
		String resultPassword = passwordEncoder.encode(password);
		user.setPassword(resultPassword);
		user.setEnabled("1");
		Message message = new Message();
		try {
			userService.addUser(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
			if(e.getMessage().equals("duplicate-username")){
				message.setResult(e.getMessage());
				message.setMessageInfo("用户名：" + user.getUsername() + "已经存在");
			}else
				message.setResult("错误！" + e.getClass().getName());
			e.printStackTrace();
		}
		return message;
	}
	
	/**
	 * 禁用用户
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/disable-user/{userId}", method = RequestMethod.GET)
	public @ResponseBody Message disableUser(Model model, HttpServletRequest request, @PathVariable Integer userId) {
		
		Message message = new Message();
		try{
			User user = new User();
			user.setId(userId);
			user.setEnabled("0");
			userService.updateUser(user, null);
		}catch(Exception e){
			e.printStackTrace();
			message.setResult(e.getClass().getName());
		}
		
		return message;
	}
	
	/**
	 * 启用用户
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/enable-user/{userId}", method = RequestMethod.GET)
	public @ResponseBody Message enableUser(Model model, HttpServletRequest request, @PathVariable Integer userId) {
		
		Message message = new Message();
		try{
			User user = new User();
			user.setId(userId);
			user.setEnabled("1");
			userService.updateUser(user, null);
		}catch(Exception e){
			e.printStackTrace();
			message.setResult(e.getClass().getName());
		}
		
		return message;
	}
	
	/**
	 * TA的作业
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/admin/student-homework-list/{userId}", method = RequestMethod.GET)
	public String ownerhomeworkListPage(Model model,
			HttpServletRequest request,
			@PathVariable("userId") Integer userId) {
		int index=1;
		if(request.getParameter("page") != null) {
			index = Integer.parseInt(request.getParameter("page"));
		}
		User userInfo = userService.getUserById(userId);
		Page<HomeWorkHistory> pageModel = new Page<HomeWorkHistory>();
		pageModel.setPageNo(index);
		pageModel.setPageSize(10);
		List<HomeWorkHistory> homeWorkHistList = homeWorkService.getHomeWorkHistByUserId(userInfo.getId(), pageModel);
		String pageStr = PagingUtil.getPagelink(index, pageModel.getTotalPage(),"","admin/student-homework-list/"+userId);
		model.addAttribute("homeWorkHistList", homeWorkHistList);
		model.addAttribute("pageStr", pageStr);
		model.addAttribute("userId", userId);
		model.addAttribute("truename",userInfo.getTruename());
		model.addAttribute("username",userInfo.getUsername());
		return "admin/user-list-homework";
	}
	/*@RequestMapping(value = "/admin/student-homeworkhisfilter-{userId}-{page}.html", method = RequestMethod.GET)
	public String homeworkHisListFilterPage(Model model,
			@PathVariable("userId") int userId,
			@PathVariable("page") int page) {
		User userInfo = userService.getUserById(userId);
		Page<HomeWorkHistory> pageModel = new Page<HomeWorkHistory>();
		pageModel.setPageNo(page);
		pageModel.setPageSize(10);
		List<HomeWorkHistory> homeWorkHistList = homeWorkService.getHomeWorkHistByUserId(userInfo.getId(), pageModel);
		String pageStr = PagingUtil.getPageBtnlink(page, pageModel.getTotalPage());
		model.addAttribute("homeWorkHistList", homeWorkHistList);
		model.addAttribute("pageStr", pageStr);
		model.addAttribute("userId", userId);
		model.addAttribute("truename",userInfo.getTruename());
		model.addAttribute("username",userInfo.getUsername());
		return "admin/user-list-homework";
	}*/
	
	/**
	 * TA的考试
	 */
	@RequestMapping(value = "/admin/student-exam-history/{userId}", method = RequestMethod.GET)
	public String userExamHistPage(Model model, HttpServletRequest request,@PathVariable Integer userId){
		int index = 1;
		if(request.getParameter("page") != null)
			index = Integer.parseInt(request.getParameter("page"));
		//System.out.println("page="+request.getParameter("page"));
		User userInfo = userService.getUserById(userId);
		Page<ExamHistory> pageModel = new Page<ExamHistory>();
		pageModel.setPageSize(10);
		pageModel.setPageNo(index);
		List<ExamHistory> hisList = examService.getUserExamHistoryListByUserId(userInfo.getId(),pageModel);
		model.addAttribute("hisList", hisList);
		String pageStr = PagingUtil.getPagelink(index, pageModel.getTotalPage(), "", "admin/student-exam-history/"+userId);
		model.addAttribute("pageStr", pageStr);
		model.addAttribute("userId",userId);
		model.addAttribute("truename",userInfo.getTruename());
		model.addAttribute("username",userInfo.getUsername());
		return "admin/user-list-exams";
	}
	
	/**
	 * 查看学生题目分析统计页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/student-analysis/{userId}", method = RequestMethod.GET)
	public String userAnalysisPage(Model model, HttpServletRequest request, @PathVariable Integer userId) {
		User userInfo = userService.getUserById(userId);
		UserQuestionHistory uqh = questionService
				.getUserQuestionHistoryByUserId(userInfo.getId());
		model.addAttribute("lastLoginTime", userInfo.getLastLoginTime());
		List<KnowledgePoint> pointList = questionService
				.getKnowledgePointByFieldId(userInfo.getFieldId(),null);
		// 岗位通用id=1
		/*List<KnowledgePoint> pointList1 = new ArrayList<KnowledgePoint>();
		if (userInfo.getFieldId() != 1)
			pointList1 = questionService.getKnowledgePointByFieldId(1,null);*/
		List<Integer> pointIdList = new ArrayList<Integer>();
		// List<StatisticsResult> srList = new ArrayList<StatisticsResult>();
		Map<Integer, Map<Integer, QuestionHistory>> history;
		//pointList.addAll(pointList1);
		// 获取知识点id列表
		for (KnowledgePoint kp : pointList) {

			pointIdList.add(kp.getPointId());
		}
		List<QuestionImproveResult> questionImproveList = questionService
				.getQuestionImproveResultByQuestionPointIdList(pointIdList);

		List<KnowledgePointAnalysisResult> kparl = new ArrayList<KnowledgePointAnalysisResult>();
		Map<Integer, QuestionHistory> rightMap = new HashMap<Integer, QuestionHistory>();
		Map<Integer, QuestionHistory> wrongMap = new HashMap<Integer, QuestionHistory>();
		if (uqh != null) {
			history = uqh.getHistory();

			if (history.containsKey(0))
				wrongMap = history.get(0);
			if (history.containsKey(1))
				rightMap = history.get(1);

		}
		for (KnowledgePoint kp : pointList) {

			KnowledgePointAnalysisResult kpar = new KnowledgePointAnalysisResult();
			kpar.setKnowledgePointId(kp.getPointId());
			kpar.setKnowledgePointName(kp.getPointName());
			List<TypeAnalysis> tal = new ArrayList<TypeAnalysis>();
			// 一个知识点内所有的题
			float totalCount = 0;
			// 做过的题（一个知识点内）
			float finishQuestionCount = 0;
			for (QuestionImproveResult qir : questionImproveList) {
				if (qir.getQuestionPointId() == kp.getPointId()) {
					//System.out.println("qir.getAmount()=" + qir.getAmount());
					TypeAnalysis t = new TypeAnalysis();
					t.setQuestionTypeId(qir.getQuestionTypeId());
					t.setQuestionTypeName(qir.getQuestionTypeName());
					t.setRestAmount(qir.getAmount());
					totalCount += qir.getAmount();
					tal.add(t);
				}
			}
			for (TypeAnalysis ta : tal) {
				Iterator<Integer> rightIt = rightMap.keySet().iterator();
				Iterator<Integer> wrongIt = wrongMap.keySet().iterator();
				int rightAmount = 0;
				int wrongAmount = 0;
				while (rightIt.hasNext()) {
					int key = rightIt.next();
					QuestionHistory tmpQh = rightMap.get(key);
					if (tmpQh.getPointId() == kp.getPointId()
							&& tmpQh.getQuestionTypeId() == ta
									.getQuestionTypeId()) {
						rightAmount++;
					}

				}
				while (wrongIt.hasNext()) {
					int key = wrongIt.next();
					QuestionHistory tmpQh = wrongMap.get(key);
					if (tmpQh.getPointId() == kp.getPointId()
							&& tmpQh.getQuestionTypeId() == ta
									.getQuestionTypeId()) {
						wrongAmount++;
					}

				}
				ta.setRightAmount(rightAmount);
				ta.setWrongAmount(wrongAmount);
				finishQuestionCount += rightAmount + wrongAmount;
				ta.setRestAmount(ta.getRestAmount() - rightAmount - wrongAmount);
			}
			kpar.setTypeAnalysis(tal);
			kpar.setFinishRate(((float) Math.round(finishQuestionCount * 1000f
					/ totalCount)) / 1000f);
			kparl.add(kpar);
		}
		model.addAttribute("kparl", kparl);
		model.addAttribute("userId",userId);
		model.addAttribute("truename",userInfo.getTruename());
		model.addAttribute("username",userInfo.getUsername());
		return "admin/user-list-analysis";
	}
	
	/**
	 * 老师查看学员用户中心信息
	 */
	@RequestMapping(value = "/admin/student-center/{userId}", method = RequestMethod.GET)
	public String studentUserCenter(Model model, HttpServletRequest request, @PathVariable Integer userId) {
		/*UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();*/
		//获取用户信息
		User userInfo = userService.getUserById(userId);
		model.addAttribute("userId",userInfo.getId());
		model.addAttribute("username", userInfo.getUsername());
		model.addAttribute("truename", userInfo.getTruename());
		model.addAttribute("email", userInfo.getEmail());
		model.addAttribute("field", userInfo.getFieldName());
		UserQuestionHistory uqh = questionService
				.getUserQuestionHistoryByUserId(userInfo.getId());
		model.addAttribute("lastLoginTime", userInfo.getLoginTime());
		List<KnowledgePoint> pointList = questionService
				.getKnowledgePointByFieldId(userInfo.getFieldId(),null);
		// 岗位通用id=1
		/*List<KnowledgePoint> pointList1 = new ArrayList<KnowledgePoint>();
		if (userInfo.getFieldId() != 1)
			pointList1 = questionService.getKnowledgePointByFieldId(1,null);*/
		List<Integer> pointIdList = new ArrayList<Integer>();
		List<StatisticsResult> srList = new ArrayList<StatisticsResult>();
		Map<Integer, Map<Integer, QuestionHistory>> history;
		//pointList.addAll(pointList1);
		// 获取知识点id列表
		if(pointList != null && pointList.size() > 0){
			for (KnowledgePoint kp : pointList) {
				pointIdList.add(kp.getPointId());
			}
			List<QuestionImproveResult> questionImproveList = questionService.getQuestionImproveResultByQuestionPointIdList(pointIdList);
			Map<Integer, Integer> pointStatisticMap = new HashMap<Integer, Integer>();
			// 获取每种知识点对应的试题数量
			for (QuestionImproveResult qir : questionImproveList) {
				int amount = 0;
				if(pointStatisticMap.containsKey(qir.getQuestionPointId()))
					amount = pointStatisticMap.get(qir.getQuestionPointId());
				//主观题不参加统计 2014-08-13
				if(qir.getQuestionTypeId() == 1 || qir.getQuestionTypeId() == 2 || qir.getQuestionTypeId() == 3 || qir.getQuestionTypeId() == 4)
					amount += qir.getAmount();
				//主观题不参加统计 2014-08-13
				//amount += pointStatisticMap.get(qir.getQuestionPointId());
				pointStatisticMap.put(qir.getQuestionPointId(), amount);
			}
			
			Map<Integer, QuestionHistory> rightMap = new HashMap<Integer, QuestionHistory>();
			Map<Integer, QuestionHistory> wrongMap = new HashMap<Integer, QuestionHistory>();
			
			for (KnowledgePoint kp : pointList) {
				StatisticsResult sr = new StatisticsResult();
				sr.setPointId(kp.getPointId());
				sr.setPointName(kp.getPointName());
				if (uqh != null) {
					history = uqh.getHistory();
					if (history.containsKey(0))
						wrongMap = history.get(0);
					if (history.containsKey(1))
						rightMap = history.get(1);
					Iterator<Integer> rightIt = rightMap.keySet().iterator();
					Iterator<Integer> wrongIt = wrongMap.keySet().iterator();
					int rightAmount = 0;
					int wrongAmount = 0;
					while (rightIt.hasNext()) {
						int key = rightIt.next();
						QuestionHistory tmpQh = rightMap.get(key);
						if (tmpQh.getPointId() == kp.getPointId())
							rightAmount++;
					}
					while (wrongIt.hasNext()) {
						int key = wrongIt.next();
						QuestionHistory tmpQh = wrongMap.get(key);
						if (tmpQh.getPointId() == kp.getPointId())
							wrongAmount++;
					}
					sr.setRightTimes(rightAmount);
					sr.setWrongTimes(wrongAmount);
					int amount = 0;
					if(pointStatisticMap.containsKey(sr.getPointId()))
						amount = pointStatisticMap.get(sr.getPointId());
					//System.out.println("amount=" + amount);
					float rightRate = rightAmount + wrongAmount != 0 ? (float) Math
							.round((float) rightAmount * 10000f / amount) / 10000f
							: 0f;
					//System.out.println("rightRate=" + rightRate);
					float finishRate = amount != 0 ? (float) Math
							.round((float) (rightAmount + wrongAmount) * 10000f
									/ amount) / 10000f : 0f;
					//System.out.println("finishRate=" + finishRate);
					sr.setRightRate(rightRate);
					sr.setFinishRate(finishRate);
				}
				sr.setAmount(pointStatisticMap.get(kp.getPointId()) == null ? 0 : pointStatisticMap.get(kp.getPointId()));
				srList.add(sr);
			}
		}
		model.addAttribute("sr", srList);
		model.addAttribute("labels", this.generateLables(srList));
		model.addAttribute("finishrate", this.generateFinishData(srList));
		model.addAttribute("correctrate", this.generateCorrectData(srList));
		return "admin/user-list-center";
	}
	
	/**
	 * 根据historyId查看学生的作业
	 * @param model
	 * @param homeWorkHistId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/homework-history-detail/{homeWorkHistId}", method = RequestMethod.GET)
	public String LookMyHomeWorkHistory(Model model, @PathVariable("homeWorkHistId") int homeWorkHistId, HttpServletRequest request) {
		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";
		HomeWorkHistory homeWorkHistory = homeWorkService.getUserHomeWorkHistoryByHistId(homeWorkHistId);
		int homeWorkId = homeWorkHistory.getHomeWorkId();
		User user = userService.getUserById(homeWorkHistory.getUserId());
		HomeWork homeWork = homeWorkService.getHomeWorkById(homeWorkId);
		StringBuilder sb = new StringBuilder();
		if(homeWorkHistory.getContent() != null && !homeWorkHistory.getContent().equals("")){
			List<QuestionQueryResult> questionList = Object2Xml.toBean(homeWorkHistory.getContent(), List.class);
			//学生提交的答案
			HashMap<Integer, AnswerSheetItem> hm = Object2Xml.toBean(homeWorkHistory.getAnswerSheet(), HashMap.class);
			//老师阅卷结果
			HashMap<Integer, TeacherReadSheetItem> hm2 = Object2Xml.toBean(homeWorkHistory.getTeacherReadSheet(), HashMap.class);
			for(QuestionQueryResult question : questionList){
				//QuestionAdapter adapter = new QuestionAdapter(hm.get(question.getQuestionId()), question, strUrl);
				//sb.append(adapter.getTeacherReviewStringFromXML());
				QuestionAdapter adapter = new QuestionAdapter(hm.get(question.getQuestionId()), hm2.get(question.getQuestionId()), question, strUrl);
				sb.append(adapter.getStudentReviewStringFromXML());
			}
		}
		model.addAttribute("userId",user.getId());
		model.addAttribute("htmlStr", sb.toString());
		model.addAttribute("homeWorkId", homeWorkId);
		model.addAttribute("homeWorkHistId", homeWorkHistId);
		model.addAttribute("homeWorkName", homeWork.getName());
		model.addAttribute("pointGet", homeWorkHistory.getPointGet());
		model.addAttribute("truename",user.getTruename());
		model.addAttribute("username",user.getUsername());
		return "admin/user-list-homework-detail";
	}
	
	/**
	 * 根据试卷ID和学生ID查看该学生的考试信息
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "admin/student-finish-exam/{examPaperId}/{userId}", method = RequestMethod.GET)
	public String paperExamFinishedPage(Model model,
			@PathVariable("examPaperId") int examPaperId,
			@PathVariable("userId") int userId) {
		User userInfo = userService.getUserById(userId);
		ExamPaper examPaper = examService.getExamPaperById(examPaperId);
		ExamHistory examHistory = examService
				.getUserExamHistoryByUserIdAndExamPaperId(userInfo.getId(),
						examPaperId);
		HashMap<Integer, AnswerSheetItem> hm = Object2Xml.toBean(
				examHistory.getAnswerSheet(), HashMap.class);
		int total = hm.size();
		int wrong = 0;
		int right = 0;
		HashMap<String, ReportResult> reportResultList = new HashMap<String, ReportResult>();
		List<QuestionQueryResult> questionQueryList = Object2Xml.toBean(
				examHistory.getContent(), List.class);
		List<Integer> idList = new ArrayList<Integer>();
		HashMap<Integer, Boolean> answer = new HashMap<Integer, Boolean>();
		for (QuestionQueryResult q : questionQueryList) {
			String pointName = q.getPointName().split(">")[1];
			idList.add(q.getQuestionId());
			if (q.getQuestionTypeId() != 1 && q.getQuestionTypeId() != 2
					&& q.getQuestionTypeId() != 3)
				continue;
			if (hm.get(q.getQuestionId()) != null) {
				if (q.getAnswer().equals(hm.get(q.getQuestionId()).getAnswer())) {
					answer.put(q.getQuestionId(), true);
					right++;
					if (reportResultList.containsKey(pointName)) {
						ReportResult r = reportResultList.get(pointName);
						r.sum++;
						r.rightTimes++;
						reportResultList.put(pointName, r);
					} else {
						ReportResult r = new ReportResult();
						r.sum = 1;
						r.rightTimes = 1;
						reportResultList.put(pointName, r);
					}
				} else {
					answer.put(q.getQuestionId(), false);
					wrong++;
					if (reportResultList.containsKey(pointName)) {
						ReportResult r = reportResultList.get(pointName);
						r.sum++;
						r.wrongTimes++;
						reportResultList.put(pointName, r);
					} else {
						ReportResult r = new ReportResult();
						r.sum = 1;
						r.wrongTimes = 1;
						reportResultList.put(pointName, r);
					}
				}
				hm.remove(q.getQuestionId());
			}
		}
		model.addAttribute("total", total);
		model.addAttribute("wrong", wrong);
		model.addAttribute("right", right);
		model.addAttribute("reportResultList", reportResultList);
		model.addAttribute("create_time", examHistory.getCreateTime());
		model.addAttribute("examPaperName",examPaper.getName());
		model.addAttribute("answer", answer);
		model.addAttribute("idList", idList);
		model.addAttribute("examPaperId", examPaperId);
		model.addAttribute("truename",userInfo.getTruename());
		model.addAttribute("username",userInfo.getUsername());
		return "admin/user-list-exams-finished";
	}
	
	/**
	 * 查看试卷详细解答
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/admin/student-exam-report/{examPaperId}/{userId}", method = RequestMethod.GET)
	public String examFinishPage(Model model,
			@PathVariable("examPaperId") int examPaperId,
			@PathVariable("userId") Integer userId,
			HttpServletRequest request) {
		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";
		User userInfo = userService.getUserById(userId);
		ExamPaper examPaper = examService.getExamPaperById(examPaperId);
		ExamHistory examHistory = examService
				.getUserExamHistoryByUserIdAndExamPaperId(userInfo.getId(),
						examPaperId);
		List<QuestionQueryResult> questionList = Object2Xml.toBean(
				examHistory.getContent(), ArrayList.class);
		HashMap<Integer, AnswerSheetItem> hm = Object2Xml.toBean(
				examHistory.getAnswerSheet(), HashMap.class);
		StringBuilder sb = new StringBuilder();
		for (QuestionQueryResult q : questionList) {
			QuestionAdapter adapter = new QuestionAdapter(hm.get(q
					.getQuestionId()), q, strUrl);
			sb.append(adapter.getReportStringFromXML());
		}
		model.addAttribute("htmlStr", sb.toString());
		model.addAttribute("examPaperId", examPaperId);
		model.addAttribute("truename",userInfo.getTruename());
		model.addAttribute("username",userInfo.getUsername());
		model.addAttribute("examPaperName",examPaper.getName());
		return "admin/user-list-exams-finished-report";
	}
	
	private String generateLables(List<StatisticsResult> srList) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < srList.size(); i++) {
			sb.append("\"");
			sb.append(srList.get(i).getPointName());
			sb.append("\"");
			if (i != srList.size() - 1)
				sb.append(",");
		}
		return sb.toString();
	}

	private String generateFinishData(List<StatisticsResult> srList) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < srList.size(); i++) {
			sb.append(srList.get(i).getFinishRate() * 100);
			if (i != srList.size() - 1)
				sb.append(",");
		}
		return sb.toString();
	}

	private String generateCorrectData(List<StatisticsResult> srList) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < srList.size(); i++) {
			sb.append(srList.get(i).getRightRate() * 100);

			if (i != srList.size() - 1)
				sb.append(",");
		}
		return sb.toString();
	}
	
	public class StatisticsResult {
		public int pointId;
		public String pointName;
		public int amount;
		public int rightTimes;
		public int wrongTimes;
		public float finishRate;
		public float rightRate;

		public float getFinishRate() {
			return finishRate;
		}

		public void setFinishRate(float finishRate) {
			this.finishRate = finishRate;
		}

		public float getRightRate() {
			return rightRate;
		}

		public void setRightRate(float rightRate) {
			this.rightRate = rightRate;
		}

		public int getPointId() {
			return pointId;
		}

		public void setPointId(int pointId) {
			this.pointId = pointId;
		}

		public String getPointName() {
			return pointName;
		}

		public void setPointName(String pointName) {
			this.pointName = pointName;
		}

		public int getAmount() {
			return amount;
		}

		public void setAmount(int amount) {
			this.amount = amount;
		}

		public int getRightTimes() {
			return rightTimes;
		}

		public void setRightTimes(int rightTimes) {
			this.rightTimes = rightTimes;
		}

		public int getWrongTimes() {
			return wrongTimes;
		}

		public void setWrongTimes(int wrongTimes) {
			this.wrongTimes = wrongTimes;
		}

	}
	public class TypeAnalysis {
		private int questionTypeId;
		private String questionTypeName;
		private int restAmount;
		private int rightAmount;
		private int wrongAmount;

		public int getQuestionTypeId() {
			return questionTypeId;
		}

		public void setQuestionTypeId(int questionTypeId) {
			this.questionTypeId = questionTypeId;
		}

		public String getQuestionTypeName() {
			return questionTypeName;
		}

		public void setQuestionTypeName(String questionTypeName) {
			this.questionTypeName = questionTypeName;
		}

		public int getRestAmount() {
			return restAmount;
		}

		public void setRestAmount(int restAmount) {
			this.restAmount = restAmount;
		}

		public int getRightAmount() {
			return rightAmount;
		}

		public void setRightAmount(int rightAmount) {
			this.rightAmount = rightAmount;
		}

		public int getWrongAmount() {
			return wrongAmount;
		}

		public void setWrongAmount(int wrongAmount) {
			this.wrongAmount = wrongAmount;
		}
	}
	public class KnowledgePointAnalysisResult {
		private int knowledgePointId;
		private String knowledgePointName;
		private List<TypeAnalysis> typeAnalysis;
		private float finishRate;

		public int getKnowledgePointId() {
			return knowledgePointId;
		}

		public void setKnowledgePointId(int knowledgePointId) {
			this.knowledgePointId = knowledgePointId;
		}

		public String getKnowledgePointName() {
			return knowledgePointName;
		}

		public void setKnowledgePointName(String knowledgePointName) {
			this.knowledgePointName = knowledgePointName;
		}

		public List<TypeAnalysis> getTypeAnalysis() {
			return typeAnalysis;
		}

		public void setTypeAnalysis(List<TypeAnalysis> typeAnalysis) {
			this.typeAnalysis = typeAnalysis;
		}

		public float getFinishRate() {
			return finishRate;
		}

		public void setFinishRate(float finishRate) {
			this.finishRate = finishRate;
		}
	}
	public class ReportResult {
		public int sum;
		public int rightTimes;
		public int wrongTimes;

		public int getSum() {
			return sum;
		}

		public int getRightTimes() {
			return rightTimes;
		}

		public int getWrongTimes() {
			return wrongTimes;
		}
	};
}
